<?php
namespace app\index\model;

use app\common\model\CommentComm;

class Comment extends CommentComm
{
    /// 用于存放子级数据
    private $child = [];
    ///获取一级评论数据
    public function getCommentData(){
        $top_map = [
            'com_show_status'  =>  array('in','0,1'),
            'parent_com_id' =>  0
        ];
        ///获取15条最新的一级评论数据{desc最新的评论显示在顶部}
        $top_comment_data = $this->where($top_map)->order('com_id desc')->limit(15)->column('com_id,parent_com_id,com_title,com_content,create_time','com_id');


        foreach ($top_comment_data as $k => $v) {
            $top_comment_data[$k]['com_content'] = htmlspecialchars_decode($v['com_content']);
            // 获取二级评论
            $this->child = [];
            $this->getTree($v);
            $child_data = $this->child;

            ///修正排序，按照评论id降序{大到小}
            if (!empty($child_data)) {
                // 按评论时间asc排序
                uasort($child_data, function ($a, $b) {
                    $prev = $a['com_id'] ?? 0;
                    $next = $b['com_id'] ?? 0;
                    if ($prev == $next) {
                        return 0;
                    }

                    return ($prev > $next) ? -1 : 1;
                });
            }
            $top_comment_data[$k]['child'] = $child_data;
        }

        return $top_comment_data;
    }
    // 递归获取评论树状结构
    private function getTree($data)
    {
        $son_map = [
            'com_show_status'  =>  array('in','0,1'),
            'parent_com_id' =>  $data['com_id'] ?? -1
        ];
        ///获取当前评论的子级数据
        $child_data = $this->where($son_map)->order('com_id desc')->column('com_id,parent_com_id,com_title,com_content,create_time','com_id');

        if (!empty($child_data)) {
            foreach ($child_data as $k => $v) {
                $v['com_content']  = htmlspecialchars_decode($v['com_content']);
                $this->child[] = $v;
                $this->getTree($v);
            }
        }
    }
}